<!--
 * @Descripttion: 
 * @version: 
 * @Author: xcb
 * @Date: 2021-04-02 10:24:14
 * @LastEditors: yangyongtao
 * @LastEditTime: 2024-03-15 11:02:30
-->
<template>
  <div class="planMain">
    <div class="top-group">
      <el-form class="searchForm" :inline="true" :model="searchData">
        <el-form-item label="方案名称">
          <el-input v-model="searchData.planName" style="margin-bottom: 8px" />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="searchData.Name" style="margin-bottom: 8px" />
        </el-form-item>
        <el-form-item label="方案状态">
          <el-select
            v-model="searchData.state"
            style="width: 195px; margin-bottom: 8px"
          >
            <el-option value="" label="全部状态"></el-option>
            <el-option value="计算中" label="计算中"></el-option>
            <el-option value="计算失败" label="计算失败"></el-option>
            <el-option value="计算完成" label="计算完成"></el-option>
            <el-option value="计算发散" label="计算发散"></el-option>
            <el-option value="尚未计算" label="尚未计算"></el-option>
            <el-option value="入库中" label="入库中"></el-option>
            <el-option value="入库失败" label="入库失败"></el-option>
            <el-option value="入库完成" label="入库完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计算时间">
          <el-date-picker
            v-model="searchData.startTime"
            type="datetime"
            format="YYYY/MM/DD hh:mm:ss"
            value-format="YYYY/MM/DD hh:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData">查询</el-button>
        </el-form-item>

        <div class="optBtn">
          <el-button type="primary" @click="addDialog.show = true">
            <template #icon><EditOutlined /> </template>
            方案新建
          </el-button>
          <el-button type="primary" style="margin: 0 15px" @click="deletePlan">
            <template #icon><DeleteOutlined /> </template>
            删除
          </el-button>
          <el-button type="primary" style="margin: 0" @click="resultBtn">
            <template #icon><LineChartOutlined /> </template>
            查看
          </el-button>
        </div>
      </el-form>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="
        tableData.data.slice(
          (currentPage - 1) * pageSize,
          currentPage * pageSize
        )
      "
      :row-key="(row) => row.planno"
      border
      stripe
      :max-height="tableHeight"
      style="min-height: 372px"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
        :selectable="(row) => row.planName != '每日预测方案'"
      />
      <el-table-column
        v-for="item in columns"
        :key="item.dataIndex"
        :prop="item.dataIndex"
        :label="item.title"
        :width="item.width"
      />
      <el-table-column label="计算进度">
        <template #default="scope">
          <el-progress
            v-if="scope.row.state === '计算中'"
            :text-inside="true"
            :stroke-width="24"
            :percentage="scope.row.schedule"
          />
        </template>
      </el-table-column>
      <el-table-column label="完成用时">
        <template #default="scope"> {{ scope.row.stateTime }} </template>
      </el-table-column>
      <el-table-column label="控制" width="350px">
        <template #default="scope">
          <div style="text-align: center; font-size: 25px">
            <el-button
              v-if="scope.row.planName != '每日预测方案'"
              :disabled="
                scope.row.state === '计算中' || scope.row.state === '入库中'
              "
              type="primary"
              @click="handleClickRow(scope.row)"
            >
              <template #icon>
                <FileTextOutlined
                  style="
                    cursor: pointer;
                    vertical-align: middle;
                    font-size: 20px;
                  "
                />
              </template>
              查看方案
            </el-button>
            <el-button
              v-if="
                scope.row.state != '计算中' || scope.row.state == '计算失败'
              "
              @click="calculation(scope.row)"
              type="primary"
            >
              <template #icon>
                <CaretRightOutlined
                  style="
                    cursor: pointer;
                    vertical-align: middle;
                    font-size: 20px;
                  "
                />
              </template>
              <span style="font-size: 15px">计算</span>
            </el-button>

            <el-button
              v-else
              @click="stop(scope.row)"
              style="
                border-color: #faa64b;
                background-color: #faa64b;
                color: #fff;
              "
            >
              <template #icon>
                <BorderOutlined
                  style="
                    cursor: pointer;
                    vertical-align: middle;
                    font-size: 20px;
                  "
                />
              </template>
              <span style="font-size: 15px">停止</span>
            </el-button>

            <el-button
              v-if="scope.row.planName != '每日预测方案'"
              :disabled="
                scope.row.state != '计算完成' && scope.row.state != '入库失败'
              "
              @click="savePlan(scope.row)"
              :class="{
                'enable-btn':
                  scope.row.state == '计算完成' ||
                  scope.row.state == '入库失败',
              }"
              style="margin-left: 10px"
            >
              <template #icon>
                <VerticalAlignBottomOutlined
                  style="
                    cursor: pointer;
                    vertical-align: middle;
                    font-size: 20px;
                  "
                />
              </template>
              <span style="font-size: 15px">保存</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      :page-sizes="[10, 15, 20, 30]"
      style="float: right; margin: 15px 15px 0 0"
      layout="sizes, prev, pager, next"
      :total="tableData.data.length"
    ></el-pagination>

    <ResultPage @clear="clear" style="height: 510px; margin-top: 60px" />

    <el-dialog v-model="addDialog.show" title="" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="方案类型">
          <el-select v-model="addDialog.planType">
            <el-option label="库区一维水沙数学模型" value="1" />
            <el-option label="河段一维水沙数学模型" value="2" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialog.show = false">取消</el-button>
          <el-button type="primary" @click="addPlan">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  PlusOutlined,
  DeleteOutlined,
  LineChartOutlined,
  ExclamationCircleOutlined,
  CaretRightOutlined,
  CloseOutlined,
  VerticalAlignBottomOutlined,
  BorderOutlined,
  EditOutlined,
  FileTextOutlined,
} from "@ant-design/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  defineComponent,
  ref,
  provide,
  inject,
  watch,
  reactive,
  createVNode,
  toRefs,
  onMounted,
  onBeforeUnmount,
} from "vue";
import {
  getPlanList,
  addYcPlan,
  removePlan,
  runYiWeiModel,
  runYiWeiModelYB,
  killHydroSim,
  reslutPlanSave,
  readLog,
  planPutStorage,
  runPython,
} from "@/request/api";

import moment, { Moment } from "moment";
import ResultPage from "@/components/resultPage.vue";

const columns = [
  {
    title: "方案名称",
    dataIndex: "planName",
    key: "planName",
    align: "center",
  },
  {
    title: "创建人",
    dataIndex: "Name",
    key: "Name",
    align: "center",
  },
  {
    title: "方案状态",
    dataIndex: "state",
    align: "center",
  },
  {
    title: "计算库区",
    dataIndex: "address",
    align: "center",
  },
  {
    title: "计算时间",
    dataIndex: "starttime",
    align: "center",
    width: "155px",
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center",
  },
];

export default defineComponent({
  components: {
    PlusOutlined,
    DeleteOutlined,
    LineChartOutlined,
    ExclamationCircleOutlined,
    CaretRightOutlined,
    FileTextOutlined,
    CloseOutlined,
    VerticalAlignBottomOutlined,
    BorderOutlined,
    EditOutlined,
    ResultPage,
  },
  setup() {
    const state = reactive({
      searchData: {
        planName: "",
        Name: "",
        state: "",
        startTime: "",
      },
      timer: undefined,
      currentPage: 1,
      pageSize: 10,
      tableHeight: "100%",
      form: {
        planno: "modelTemp",
        planName: "",
        remark: "",
      },
      tableData: {
        data: [],
      },
      showResultPage: false,

      addDialog: {
        show: false,
        planType: "1",
      },
    });

    const formRef = ref();
    const multipleSelection = ref([]);
    const resultNum = ref(0);
    const multipleTableRef = ref();

    const rules = {
      planName: [
        {
          required: true,
          message: "请输入方案名称",
          trigger: "blur",
        },
      ],
    };

    let spinning: any = inject("spinning");

    provide("resultNum", resultNum);
    provide("multipleSelection", multipleSelection);

    onMounted(() => {
      getTableData();
      clearInterval(state.timer);
      state.timer = null;
      state.timer = setInterval(() => {
        getTableData();
      }, 5000);
    });

    onBeforeUnmount(() => {
      clearInterval(state.timer);
      state.timer = null;
    });

    function getTableData() {
      let tableData = [],
        scheduleData = [];

      const planList = new Promise<void>((resolve) => {
        let obj = { ...state.searchData };

        obj.startTime = obj.startTime ? obj.startTime : "";
        getPlanList(obj)
          .then((res: any) => {
            tableData = res.filter((item) => {
              if (item.state === "") {
                item.state = "尚未计算";
              }
              if (item.starttime) {
                item.starttime = moment(item.starttime).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
              }
              if (item.address === "sfps") {
                item.typeName = "沙峰排沙调度";
              } else if (item.address === "kwjy") {
                item.typeName = "库尾减淤调度";
              }
              return item;
            });
          })
          .finally(() => {
            resolve();
          });
      });

      const scheduleList = new Promise<void>((resolve) => {
        readLog({})
          .then((res: any) => {
            scheduleData = res.data;
          })
          .finally(() => {
            resolve();
          });
      });

      Promise.all([planList, scheduleList])
        .then((res) => {
          scheduleData.forEach((item) => {
            let index = tableData.findIndex((ele) => {
              return ele.planno === item.planno;
            });

            if (index != -1 && item.DoneP) {
              tableData[index].schedule = Number(
                item.DoneP.substring(0, item.DoneP.length - 2)
              );
            }
          });
        })
        .finally(() => {
          state.tableData.data = tableData;
        });
    }

    const clear = () => {
      state.tableHeight = "100%";
      multipleSelection.value = [];
    };

    return {
      ...toRefs(state),
      columns,
      formRef,
      rules,
      spinning,
      multipleTableRef,
      multipleSelection,
      resultNum,

      getTableData,
      clear,
    };
  },

  methods: {
    handleClickRow(row: any) {
      clearInterval(this.timer);

      this.timer = "";
      let startDate = row.datastarttime,
        endDate = row.dataendtime;

      this.$router.push({
        name: "schemePreset",
        params: {
          planno: row.planno,
          argumentsid: row.argumentsid,
          msno: row.msno,
          planName: row.planName,
          address: row.address,
          pageType: row.address,
          isEdit: true,
          startDate,
          endDate,
        },
      });
    },
    resultBtn() {
      // table表格高度切换
      this.tableHeight = document.body.clientHeight * 0.4;

      // 已选择的方案清空
      this.multipleSelection = [];

      // 获取所有已选中的方案
      const selectPlan = this.multipleTableRef.getSelectionRows();

      // 非计算完成/入库完成状态的方案
      const stateArr = selectPlan.filter(
        (item) => item.state != "计算完成" && item.state != "入库完成"
      );

      // 所选方案中含有的所有库区
      const addressArr = Array.from(
        new Set(selectPlan.map((item) => item.address))
      );

      if (selectPlan.length == 0) {
        ElMessage.error("请选择一个方案");
      } else if (stateArr.length != 0) {
        // 判断方案是不是全部已完成
        ElMessage.error("请选择计算完成或者入库完成的方案");
      } else if (addressArr.length != 1) {
        // 判断是否含有多个库区
        ElMessage.error("请选择同一库区的方案进行成果对比");
      } else {
        this.multipleSelection = selectPlan;
      }
    },
    addPlan() {
      clearInterval(this.timer);
      this.timer = "";

      this.$router.push({
        name: "schemePreset",
        params: {
          planno: "",
          isEdit: false,
          addType: this.addDialog.planType,
        },
      });
    },
    deletePlan() {
      // 获取已选择的方案列表
      const selectPlan = this.multipleTableRef.getSelectionRows();

      if (selectPlan.length == 0) {
        ElMessage.error("请选择一个方案");
        return;
      }

      const that = this;

      ElMessageBox({
        title: "警告",
        message: "确认删除所选方案？",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            that.spinning = true;

            clearInterval(that.timer);
            that.timer = null;
            that.timer = setInterval(() => {
              that.getTableData();
            }, 5000);

            removePlan({
              plannos: selectPlan
                .map((item) => {
                  return item.planno;
                })
                .join(","),
            })
              .then((res: any) => {
                if (res.code == 1) {
                  ElMessage.success(res.msg);
                  that.multipleTableRef.clearSelection();

                  setTimeout(() => {
                    instance.confirmButtonLoading = false;
                  }, 300);
                } else {
                  ElMessage.error(res.msg);
                }
              })
              .finally(() => {
                that.spinning = false;
                that.getTableData();
              });
          }
          done();
        },
      });
    },
    calculation(val) {
      ElMessage.success("开始计算方案");
      val.state = "计算中";
      if (val.address === "长江中下游") {
        runPython({
          pathId: val.planno,
        }).then((res) => {});
      } else {
        if (val.planName == "每日预测方案")
          runYiWeiModelYB({ planno: val.planno });
        else runYiWeiModel({ planno: val.planno });
      }

      setTimeout(() => {
        this.getTableData();
      }, 5000);
    },
    stop(val) {
      clearInterval(this.timer);
      this.timer = "";
      this.timer = setInterval(() => {
        this.getTableData();
      }, 5000);

      killHydroSim({ planno: val.planno }).then((res) => {
        ElMessage.success("停止计算成功");
        setTimeout(() => {
          this.getTableData();
        }, 5000);
      });
    },
    savePlan(val) {
      val.state = "入库中";

      clearInterval(this.timer);
      this.timer = "";
      this.timer = setInterval(() => {
        this.getTableData();
      }, 5000);

      if (val.address === "长江中下游") {
        planPutStorage({
          planNo: val.planno,
          planCd: val.username,
          startDate: val.datastarttime,
          endDate: val.dataendtime,
        }).then((res: any) => {
          if (res.code == 200) {
            ElMessage.success("文件入库成功");
            this.getTableData();
          } else {
            ElMessage.error("文件入库失败");
          }
        });
      } else {
        reslutPlanSave({
          planno: val.planno,
          planName: val.planName,
        }).then((res: any) => {
          if (res.code == 1) {
            ElMessage.success("文件入库成功");
            this.getTableData();
          } else {
            ElMessage.error("文件入库失败");
          }
        });
      }
    },
  },
});
</script>

<style scoped lang="less">
.planMain {
  height: 100%;
  .top-group {
    border: 1px solid #ccc;
    overflow: hidden;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 10px;
    .optBtn {
      float: right;
      margin-top: 5px;
    }
  }
}

.stopBox {
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 14px;
  vertical-align: middle;
  cursor: pointer;
}

.enable-btn {
  border-color: #52d3c7;
  background-color: #52d3c7;
  color: #fff;
}
.enable-btn:hover {
  border-color: #52d3c7;
  background-color: #52d3c7;
  color: #fff;
}
</style>
